import React, { Component } from 'react'
import {Text, View, StyleSheet, FlatList, RefreshControl, TouchableOpacity, Image, DeviceEventEmitter } from 'react-native';
import ReadDao from '../../js/expand/dao/ReadDao'
import CollectionDao from '../../js/expand/dao/CollectionDao'

export default class ReadTab extends Component {
  constructor(props) {
    super(props);
    this.readDao = new ReadDao();
    this.collextionDao = new CollectionDao();
    this.state = {
      result: [],
      loading: false
    }
  }
  
  componentDidMount() {
    this.loadDate();
    DeviceEventEmitter.addListener('collect', (e) => {
      // handle event.
      if(!e) {
        return;
      }
      this.like(e)
    });
  }

  componentWillReceiveProps() {
    this.loadDate();
  }

  loadDate() {
    this.setState({
      loading: true
    })
    if(this.props.id === 'collectDao') {
      this.collextionDao.getData().then(res => {
        console.log('collect', res)
        if(res) {
          this.setState({
            result: res,
            loading: false
          })
        }
      })
    }else {
      let url = 'https://api.yeshaojun.com/api/article/typelist?title='+ (this.props.id == 'ALL' ? '' : this.props.id)
      this.readDao.getData(url).then(res => {
        if(res) {
          this.collextionDao.checkData([...res]).then(result=> {
            this.setState({
              result: result,
              loading: false
            })
          })
  
        }else {
          fetch(url)
          .then((response) => response.json())
          .then((res)=> {
            this.collextionDao.checkData([...res.data]).then(result=> {
              this.setState({
                result: result,
                loading: false
              })
              this.readDao.saveData(url, result)
            })
          })
          .catch((error) => {
            alert(error)
          });
        }
      })
    }
  }

  goDetail(item) {
    this.props.navigation.push('ReadDetail', {id: item.id, name: item.title, show: item})
  }

  renderTime(time) {
    return time.split(' ')[0]
  }

  renderContent(obj) {
    let str = ''
    if(obj.length>80) {
      str = obj.substring(0,80) + '......'
    } else {
      str = obj
    }
    return str;
  }

  componentWillUnmount = () => {
    this.setState = (state,callback)=>{
      return;
    };
  }

  like (item) {
    let arr = [...this.state.result];
    for(let i=0; i< arr.length; i++) {
      if(arr[i].id === item.id) {
        arr[i].show = ! arr[i].show
        // 添加
        if(arr[i].show) {
          this.collextionDao.saveData(item)
        } else {
          this.collextionDao.removeData(item)
        }
      }
    }
    this.setState({
      result: arr
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.result}
          renderItem={
            ({item}) => {
              return (
                <View key={item.id} style={styles.list}>
                  <TouchableOpacity onPress={this.goDetail.bind(this, item)}>
                    <Text style={styles.title}>{item.title}</Text>
                    <Text style={styles.content}>{this.renderContent(item.introduction)}</Text>
                    <View style={{flexDirection: 'row',justifyContent: 'space-between'}}>
                      <Text style={styles.time}>{this.renderTime(item.create_time)}</Text>
                      <TouchableOpacity onPress={this.like.bind(this, item)}>
                        <Image style={styles.img} source={
                          item.show ? require('../images/ic_star.png') : require('../images/ic_unstar_transparent.png')
                        } tintColor={this.props.themeColor}/>
                      </TouchableOpacity>
                    </View>
                  </TouchableOpacity>
                </View>
              )
            }
          }
          refreshControl ={
            <RefreshControl 
              title="Loding"
              colorRendering="red"
              colors={['red']}
              tintColor={this.props.themeColor}
              refreshing={this.state.loading}
              onRefresh={
                ()=> {
                  this.loadDate()
                }
              }
            />
          }
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  list: {
    backgroundColor: 'white',
    padding: 10,
    marginLeft: 5,
    marginRight: 5,
    marginVertical: 3,
    borderWidth: 0.5,
    borderColor: '#ddd',
    shadowColor: 'gray',
    shadowOffset: {width: 0.5, height: 0.5},
    shadowOpacity: 0.4,
    shadowRadius: 1,
    elevation: 2
  },
  title: {
    fontSize: 14,
    color: '#333'
  },
  content: {
    paddingTop: 4,
    fontSize: 12,
    color: '#999',
    paddingRight: 30,
  },
  time: {
    paddingTop: 4,
    fontSize: 12,
    color: '#333'
  },
  img: {
    width: 20,
    height: 20
  }
})